package com.beiye.drivertransport.illegallearningfragment;


import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.SubActivity.IllegallearningCourseDetailsActivity;
import com.beiye.drivertransport.SubActivity.SpecifiedLearningCourseDetailsAgainActivity;
import com.beiye.drivertransport.bean.ClassLearningBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.fragment.TwoBaseFgt;
import com.beiye.drivertransport.utils.CameraCanUseUtils;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import okhttp3.Call;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
//学习类别
public class ClassLearningFragment extends TwoBaseFgt {


    ExpandableListView illegal_lv;

    View empty_view;

    private MyExpandableListViewAdapter adapter;
    private List<ClassLearningBean.RowsBean> ParentList = new ArrayList<>();
    Map<ClassLearningBean.RowsBean, List<ClassLearningBean.RowsBean.CourseListBean>> dataset = new HashMap<>();


    @Override
    public int getLayoutId() {
        return R.layout.fragment_class_learning;

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void initData() {
        illegal_lv = (ExpandableListView) getActivity().findViewById(R.id.illegal_expandablelistview);
        empty_view = (View) getActivity().findViewById(R.id.empty_view);

        if (getArguments() != null) {
             int  uvtSn = getArguments().getInt("uvtSn");//培训系列号
        //    int   mark = getArguments().getInt("mark");
            SharedPreferences sp = getActivity().getSharedPreferences("uvtSnandmark",
                    Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putInt("uvtSn",uvtSn);
       //     edit.putInt("mark",mark);
            edit.commit();
        }
        initUi();
    }

    private void initUi() {
        illegal_lv.setGroupIndicator(null);//去掉箭头
        illegal_lv.setEmptyView(empty_view);
        illegal_lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {

                    if (!CameraCanUseUtils.isCameraCanUse()) {

                        ToastUtil.showShortToast(getActivity(), "请到手机设置界面里找驾运宝允许开启照相");
                    } else {

                        if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getFinishMark() == 0) {
                            showLoadingDialog("正在加载");
                            int tcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getTcSn();
                            int sn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getSn();
                            int havedLength=dataset.get(ParentList.get(groupPosition)).get(childPosition).getHavedLength();
                            Bundle bundle = new Bundle();
                            bundle.putInt("tcsn", tcSn);
                            bundle.putInt("sn", sn);
                            bundle.putInt("minPer", 100);
                            bundle.putInt("havedLength",havedLength);
                            startActivity(IllegallearningCourseDetailsActivity.class, bundle);

                        } else if (dataset.get(ParentList.get(groupPosition)).get(childPosition).getFinishMark() == 1) {
                            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(getActivity());
                            builder1.setMessage("您已学习了该课程，继续浏览课程将不记录时间");
                            builder1.setTitle("提示:");
                            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    int tcSn = dataset.get(ParentList.get(groupPosition)).get(childPosition).getTcSn();
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("tcsn", tcSn);
                                    startActivity(SpecifiedLearningCourseDetailsAgainActivity.class, bundle);
                                    //设置你的操作事项
                                }
                            });
                            builder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                }
                            });
                            builder1.create().show();

                        }
                    }

                return true;
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        dismissLoadingDialog();
        requestData();
    }
    @Override
    public void requestData() {

        SharedPreferences sp = getActivity().getSharedPreferences("uvtSnandmark",
                Context.MODE_PRIVATE);
        int uvtSn = sp.getInt("uvtSn", 0);

        //违章学习-学习类别
        OkGo.get(AppInterfaceConfig.BASE_URL+"course/userViolationTCourse/query/"+uvtSn)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        ClassLearningBean classLearningBean = JSON.parseObject(result, ClassLearningBean.class);
                        List<ClassLearningBean.RowsBean> rows = classLearningBean.getRows();
                        ParentList.clear();
                        dataset.clear();
                        ParentList.addAll(rows);
                        for (int i = 0; i < ParentList.size(); i++) {
                            List<ClassLearningBean.RowsBean.CourseListBean> courseList = ParentList.get(i).getCourseList();
                            dataset.put(ParentList.get(i), courseList);
                        }
                        adapter = new MyExpandableListViewAdapter(getContext(), ParentList, dataset);
                        illegal_lv.setAdapter(adapter);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);

                    }
                });

    }


    private class MyExpandableListViewAdapter extends BaseExpandableListAdapter {

        private Context context;
        private List<ClassLearningBean.RowsBean> ParentList;
        private Map<ClassLearningBean.RowsBean, List<ClassLearningBean.RowsBean.CourseListBean>> dataset;

        public MyExpandableListViewAdapter(Context context, List<ClassLearningBean.RowsBean> ParentList, Map<ClassLearningBean.RowsBean, List<ClassLearningBean.RowsBean.CourseListBean>> dataset) {
            this.context = context;
            this.ParentList = ParentList;
            this.dataset = dataset;
        }


        //  获得某个父项的某个子项
        @Override
        public Object getChild(int parentPos, int childPos) {

            return dataset.get(ParentList.get(parentPos)).get(childPos);

        }

        //  获得父项的数量
        @Override
        public int getGroupCount() {
            return dataset.size();
        }

        //  获得某个父项的子项数目
        @Override
        public int getChildrenCount(int parentPos) {

            return dataset.get(ParentList.get(parentPos)).size();
        }

        //  获得某个父项
        @Override
        public Object getGroup(int parentPos) {
            return dataset.get(ParentList.get(parentPos));
        }

        //  获得某个父项的id
        @Override
        public long getGroupId(int parentPos) {
            return parentPos;
        }

        //  获得某个父项的某个子项的id
        @Override
        public long getChildId(int parentPos, int childPos) {
            return childPos;
        }

        //  按函数的名字来理解应该是是否具有稳定的id，这个方法目前一直都是返回false，没有去改动过
        @Override
        public boolean hasStableIds() {
            return false;
        }

        //  获得父项显示的view
        @Override
        public View getGroupView(int parentPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.parent_illegal_item, null);
            }
            view.setTag(R.layout.parent_illegal_item, parentPos);
            view.setTag(R.layout.child_item1, -1);

            ImageView img_parent = (ImageView) view.findViewById(R.id.img_parent);
            TextView parent_line = (TextView) view.findViewById(R.id.parent_line);
            TextView tv_title = (TextView) view.findViewById(R.id.tv_parent);
            LinearLayout re_nodata =(LinearLayout) view.findViewById(R.id.re_nodata);//子类无数据
            if (ParentList != null && parentPos < ParentList.size()) {
                tv_title.setText(ParentList.get(parentPos).getVttName());
                LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams) parent_line.getLayoutParams(); //取控件textView当前的布局参数
                if (b)//判断展开
                {
                    if(ParentList.get(parentPos).getCourseList().size()==0)
                    {
                        re_nodata.setVisibility(View.VISIBLE);
                    }
                    img_parent.setImageResource(R.mipmap.jianhao);
                    linearParams.height = 3;// 控件的高强制设成3
                    parent_line.setLayoutParams(linearParams);

                } else {
                    re_nodata.setVisibility(View.GONE);
                    img_parent.setImageResource(R.mipmap.jiahao);
                    linearParams.height = 30;// 控件的高强制设成16
                    parent_line.setLayoutParams(linearParams);
                }
            }


            return view;
        }

        //  获得子项显示的view
        @Override
        public View getChildView(int parentPos, int childPos, boolean b, View view, ViewGroup viewGroup) {
            if (view == null) {
                LayoutInflater inflater = (LayoutInflater) getActivity()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = inflater.inflate(R.layout.child_item1, null);
            }
            view.setTag(R.layout.parent_illegal_item, parentPos);
            view.setTag(R.layout.child_item1, childPos);
            TextView tv_ttName = (TextView) view.findViewById(R.id.tv_child);
            TextView tv_courseName = (TextView) view.findViewById(R.id.tv_child2);
            TextView tv_courseLength = (TextView) view.findViewById(R.id.tv_child3);
            TextView tv_studyState = (TextView) view.findViewById(R.id.tv_child4);
            tv_ttName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getTtName());
            tv_courseName.setText(dataset.get(ParentList.get(parentPos)).get(childPos).getCourseName());
            tv_courseLength.setText("课程时长:" + dataset.get(ParentList.get(parentPos)).get(childPos).getReadLength() + "分钟");

            int finishMark = dataset.get(ParentList.get(parentPos)).get(childPos).getFinishMark();
            int havedLength= dataset.get(ParentList.get(parentPos)).get(childPos).getHavedLength(); //已阅读时长

            if (finishMark == 0) {

                if (havedLength > 0) {
                    tv_studyState.setBackgroundResource(R.drawable.stroke_orange_2);
                    tv_studyState.setTextColor(getResources().getColor(R.color.orange_namesecond));
                    tv_studyState.setText("未完成");
                } else {
                    tv_studyState.setBackgroundResource(R.drawable.stroke_red_2);
                    tv_studyState.setTextColor(getResources().getColor(R.color.red_gray));
                    tv_studyState.setText("去学习");
                }
            } else if (finishMark == 1) {
                tv_studyState.setBackgroundResource(R.drawable.stroke_green_2);
                tv_studyState.setTextColor(getResources().getColor(R.color.green_gray));
                if (havedLength > 0) {
                    tv_studyState.setText("已学习");
                }
            }

            /*if (dataset.get(ParentList.get(parentPos)).get(childPos).getFinishMark() == 0) {
                tv_studyState.setImageResource(R.mipmap.wxx);
            } else if (dataset.get(ParentList.get(parentPos)).get(childPos).getFinishMark() == 1) {
                tv_studyState.setImageResource(R.mipmap.yxx);
            }*/


            return view;
        }

        //  子项是否可选中，如果需要设置子项的点击事件，需要返回true
        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }







    @Override
    public void onUserVisible() {

    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }
}
